﻿using System;
using System.Collections.Generic;
using System.Linq;
using Kevin.Shop.Business.Core.Member;
using Kevin.Shop.Business.Service.Entity.Helper;
using RiderShop.Mobile.Common.Component;

namespace RiderShop.Mobile.Common.Helper
{
    public class CacheUsers
    {
        private const string CacheKey = "User_{0}";
        private static Dictionary<string, UserBasicInfo> cacheList = new Dictionary<string, UserBasicInfo>();

        public static void Update(UserBasicInfo user)
        {
            string key = string.Format(CacheKey, user.UserName);
            if (!cacheList.ContainsKey(key))
            {
                cacheList.Add(key, user);
            }
            else
            {
                cacheList[key] = user;
            }

            var list = cacheList.Where(p => (p.Value.LastActivity < System.DateTime.Now.AddMinutes(-240)));
            var keyValuePairs = list as KeyValuePair<string, UserBasicInfo>[] ?? list.ToArray();
            for (int i = 0; i < keyValuePairs.Count(); i++)
            {
                if (cacheList.Any(p => (p.Key.ToLower() == keyValuePairs[i].Key.ToLower())))
                {
                    cacheList.Remove(keyValuePairs[i].Key);
                }
            }
        }

        public static UserBasicInfo Get(string userName, bool cached)
        {
            return Get(0, userName, cached);
        }

        public static UserBasicInfo Get(int userId, bool cached)
        {
            return Get(userId, string.Empty, cached);
        }

        public static UserBasicInfo Get(int userId, string userName, bool cached)
        {
            UserBasicInfo userInfo = null;
            if (userId > 0 && cached)
            {
                var user = cacheList.FirstOrDefault(p => (p.Value.UserId == userId));
                userInfo = user.Value;
            }
            else if (!string.IsNullOrEmpty(userName) && cached && cacheList.ContainsKey(string.Format(CacheKey, userName)))
            {
                userInfo = cacheList[string.Format(CacheKey, userName)];
            }
            if (userInfo != null)
            {
                return userInfo;
            }
            //get user by service
            if (userInfo == null && userId > 0)
            {
                userInfo = RestfulHelper.QueryWithSingle<UserBasicInfo>(SiteUrl.FormatUrl("Common_GetUserInfo", userId));
            }
            else if (!string.IsNullOrEmpty(userName))
            {
                userInfo = RestfulHelper.QueryWithSingle<UserBasicInfo>(SiteUrl.FormatUrl("Common_GetUserInfoByName", userName));
            }

            if (userInfo != null)
            {
                userInfo.LastActivity = DateTime.Now;
                Update(userInfo);
            }
            return userInfo;
        }
    }
}
